package lesson8.chat.server;

import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * <br/>
 * Created on : 2018-01-29 23:18
 * @author lizebin
 */
public class ServerHandler extends SimpleChannelInboundHandler<String> {

	/**
	 * 所有客户端的Channel都放到里面
	 */
	private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	/**
	 * 广播发送给其他客户端
	 * @param ctx
	 * @param msg
	 * @throws Exception
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		Channel channel = ctx.channel();
		CHANNEL_GROUP.forEach(item -> {
			if(item != channel) {
				item.writeAndFlush(item.remoteAddress() + "发送消息:" + msg + "\n");
			} else {
				item.writeAndFlush("【自己】" + msg + "\n");
			}
		});
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		System.out.println("客户端连接:" + channel.remoteAddress());
		//自动遍历
		CHANNEL_GROUP.writeAndFlush("【服务器】- " + channel.remoteAddress() + "加入\n");
		CHANNEL_GROUP.add(channel);
	}

	/**
	 * 表示连接断开
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		System.out.println("客户端断开:" + channel.remoteAddress());
		CHANNEL_GROUP.writeAndFlush("【服务器】- " + channel.remoteAddress() + "离开\n");
		//netty 会自动从 group 中移除
		//CHANNEL_GROUP.remove(channel);
	}
}
